package com.itheima.controller;


import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.exceptions.BusinessException;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.CookiesUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("member")
public class MemberController {


    @Reference(version = "1.0.0")
    private MemberService memberService;

    @Resource
    private JedisPool jedisPool;


    /**
     * ZS
     * 根据档案number查询member
     *
     * @return 直接返回member
     */
    @GetMapping("findByFileId")
    public Result findByFileId(HttpServletRequest request) {
        String phoNumber = CookiesUtils.getCookie(request, "login_member_telephone");
        Member member = memberService.findByPhoneNumber(phoNumber);
        if (member == null) {
            return new Result(false, "没有该档案");
        }
        return new Result(true, "查询成功", member);

    }


    @PostMapping("send4Login")
    public Result send4Login(String telephone) {
        Jedis resource = null;
        try {
            //发送验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            System.out.println("登录验证码：" + code);
            //将手机验证码存入redis中，失效时间5分钟
            resource = jedisPool.getResource();
            resource.setex("LOGIN_" + telephone, 5 * 60, code.toString());
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(MessageConstant.SEND_VALIDATECODE_FAIL);
        } finally {
            if (resource != null) {
                resource.close();
            }
        }
    }

    @PostMapping("login")
    public Result login(@RequestBody Map<String, String> map, HttpServletResponse response) {
        String telephone = map.get("telephone");
        //获取验证码并与数据库进行比对
        String validateCode = map.get("validateCode");
        Jedis client = jedisPool.getResource();
        String code = client.get("LOGIN_" + map.get("telephone"));
        client.close();
        if (code == null || !code.equals(validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //获取是否有会员
        Member member = memberService.findByPhoneNumber(telephone);
        if (member == null) {
            //不是会员，自动注册
            member = new Member();
            member.setPhoNumber(telephone);
            member.setRegTime(new Date());
            memberService.add(member);
        }
        //是会员，直接登录
        //写入Cookie，跟踪用户
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        //路径
        cookie.setPath("/");
        //存活30天
        cookie.setMaxAge(60 * 60 * 24 * 30);
        response.addCookie(cookie);
        //保存会员信息到Redis中
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex("LOGIN_INFO_" + telephone, 60 * 30, json);
        /*String memberJSON = client.get("LOGIN_INFO" + map.get("telephone"));
        Member parseMember = (Member) JSONUtils.parse(memberJSON);
        long fileNumber = parseMember.getFileNumber();*/
        long fileNumber = member.getFileNumber();
        Cookie cookie1 = new Cookie("login_member_fileNumber", String.valueOf(fileNumber));
        cookie1.setPath("/");
        cookie1.setMaxAge(60 * 60 * 24 * 30);
        response.addCookie(cookie1);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
